package com.hanscan.gui;

import com.hanscan.persistence.controllers.EventJpaController;
import com.hanscan.persistence.entities.Event;
import com.hanscan.persistence.entities.User;
import com.hanscan.util.language.LanguageConfig;
import com.icesoft.faces.component.commandsortheader.CommandSortHeader;
import com.icesoft.faces.component.ext.HtmlCommandButton;
import com.icesoft.faces.component.ext.HtmlInputSecret;
import com.icesoft.faces.component.ext.HtmlInputText;
import com.icesoft.faces.component.ext.HtmlOutputLabel;
import com.icesoft.faces.component.ext.HtmlOutputText;
import com.icesoft.faces.component.ext.UIColumns;
import com.icesoft.faces.component.jsfcl.data.DefaultSelectionItems;
import com.icesoft.faces.component.jsfcl.data.PopupBean;
import com.icesoft.faces.component.panelstack.PanelStack;
import com.sun.rave.web.ui.appbase.AbstractFragmentBean;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import javax.faces.FacesException;
import javax.faces.event.ActionEvent;
import javax.faces.model.ArrayDataModel;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;


public class ManagementSingning extends AbstractFragmentBean
{
    private PanelStack panelStack = new PanelStack();
    private DataModel rowModel;
    private DataModel columnsModel;
    private CommandSortHeader dayHeader = new CommandSortHeader(); //Da el dia del mes que pinchamos
    private HtmlOutputText outputTextCell = new HtmlOutputText();
    private User user;
    private HtmlOutputLabel labelTotalWorkingDays = new HtmlOutputLabel();
    private HtmlOutputLabel labelTotalWorkingHours = new HtmlOutputLabel();
    private HtmlOutputLabel labelTotalWorkingDaysResult = new HtmlOutputLabel();
    private HtmlOutputLabel labelEstimatedHoursResult = new HtmlOutputLabel();
    private HtmlOutputLabel labelEstimatedHours = new HtmlOutputLabel();
    private HtmlOutputLabel labelTitlePanelMonthlySummary = new HtmlOutputLabel();
    private HtmlOutputLabel labelTotalWorkingHoursResult = new HtmlOutputLabel();
    private HtmlOutputLabel labelDifferenceTime = new HtmlOutputLabel();
    private HtmlOutputLabel labelDifferenceTimeResult = new HtmlOutputLabel();





    
    private UIColumns columnsMonth = new UIColumns();    
    private HtmlOutputLabel labelTittle = new HtmlOutputLabel();
    private PopupBean panelPopup1Bean = new PopupBean();
    //Mensajes popUp
    private DefaultSelectionItems panelSeries1Bean = new DefaultSelectionItems();   
    private String colorEmptyField = "background-color:rgba(255, 0, 0, 0.5);";
    private String messageHeader = new String();
    //filtros
    private HtmlCommandButton btnClosePopUp = new HtmlCommandButton();
    private String headerPopUp ="";
    private List<User> userList = new ArrayList();
    private User[] users;

    // flat to indicate multiselect row enabled.
    private boolean multiRowSelect;

    // we only want to resort if the oder or column has changed.
    private String oldSort;
    private boolean oldAscending;



    private int idNumberEdit = 0;
    String[] arrayArrivalTime=null;
    String[] arrayExitTime=null;
    String[] arrayTotalHours=null;


    private void _init() throws Exception
    {
        //loadLanguage(getSessionBean1().getSessionBeanLanguage());
        //user = getSessionBean1().getUser();
        //setPanelPopUp("", false);
    }

    public ManagementSingning()
    {
        //resetValues();
    }

    /**
     *
     * @param languageConfig
     */
    protected void loadLanguage(LanguageConfig languageConfig)
    {
        labelTittle.setValue(languageConfig.getProperty("Gestion_Clientes"));
        //Mensajes

        btnClosePopUp.setValue(languageConfig.getProperty("Cerrar"));
        //headerPopUp = languageConfig.getProperty("Fichajes_Dia");



        if (arrayArrivalTime != null)
        {
            arrayArrivalTime[0] = languageConfig.getProperty("Hora_Entrada");
        }

        if (arrayExitTime != null)
        {
            arrayExitTime[0] = languageConfig.getProperty("Hora_Salida");
        }

        if (arrayTotalHours != null)
        {
            arrayTotalHours[0] = languageConfig.getProperty("Total_Horas");
        }


        if ( (arrayArrivalTime != null) &&
             (arrayExitTime != null) &&
             (arrayTotalHours != null))
        {
            List listSingningViewTable = new ArrayList<ArrayList>();
            listSingningViewTable.add(0,
                new ArrayList(Arrays.asList(arrayArrivalTime)));
            listSingningViewTable.add(1,
                new ArrayList(Arrays.asList(arrayExitTime)));
            listSingningViewTable.add(2,
                new ArrayList(Arrays.asList(arrayTotalHours)));
            rowModel= new ListDataModel(listSingningViewTable);
        }
    }

    /**
     *
     * @param e
     * @return
     */
    public String btnClosePopUp_action(ActionEvent e)
    {
        setPanelPopUp("", false);
        return null;
    }

    public void resetValues()
    {

    }

    public void updateNumberColumns()
    {
        Calendar calendarToDay = Calendar.getInstance();
        int daysMoth = getDaysOfMonth(calendarToDay.get(Calendar.YEAR),calendarToDay.get(Calendar.MONTH))+1;
        String[] arrayNumberDay = new String[daysMoth];
        arrayNumberDay[0] = "";
        for (int i = 1; i < daysMoth; i++)
        {
            arrayNumberDay[i] = String.valueOf(i);
        }
        columnsModel = new ArrayDataModel(arrayNumberDay);
    }

    /**
     * Metodo para mostrar el resumen de fichajes diarios cuando se pincha en
     * el link del dia
     * @return
     */
    public String commandLinkDailyQuery_action()
    {
//        Calendar calendarToDay = Calendar.getInstance();
//        int dia = Integer.parseInt(dayHeader.getColumnName());
//        calendarToDay.set(Calendar.DAY_OF_MONTH, dia);
//        Date date = new Date();
//        date.setTime(calendarToDay.getTimeInMillis());
//
//        String header =headerPopUp +" "+ dia;
//
//        EventJpaController eventJpaController = new EventJpaController();
//        List<Event> lEvent = eventJpaController.findSigningByClientAndDay(user.getUserId() , date);
//
//        String[] array = new String[lEvent.size()];
//        for(int i = 0; i < lEvent.size(); i++)
//        {
//            String string = new String();
//            Calendar ci = Calendar.getInstance();
//            ci.setTimeInMillis(lEvent.get(i).getDateTime().getTime());
//
//            int minutes = ci.get(Calendar.MINUTE);
//            String sMinute = new String();
//            if(minutes<10)
//            {
//                sMinute = "0"+String.valueOf(minutes);
//            }
//            else
//            {
//                 sMinute = String.valueOf(minutes);
//            }
//            string = lEvent.get(i).getEventType().getDescription() +"-- "+ ci.get(Calendar.HOUR_OF_DAY)+":"+sMinute;
//            array[i] = string;
//        }
//        String[] arrayAux = new String[lEvent.size()];
//        if(array.length % 2 == 0)
//        {
//            for(int i = 0; i < array.length; i++)
//            {
//                if(i % 2 == 0)
//                {
//                    arrayAux[i]=array[i+1];
//                }
//                else
//                {
//                    arrayAux[i]=array[i-1];
//                }
//            }
//        }
//        else
//        {
//            for(int i = 0; i < array.length-1; i++)
//            {
//                if(i % 2 == 0)
//                {
//                    arrayAux[i]=array[i+1];
//                }
//                else
//                {
//                    arrayAux[i]=array[i-1];
//                }
//            }
//            arrayAux[array.length-1]=array[array.length-1];
//        }
//        panelSeries1Bean.setItems(arrayAux);
//        setPanelPopUp(header, true);
        return null;
    }

    /**
     * Rellena la tabla con los datos de los fichajes
     * @return
     */
    public Object getCellValue()
    {
        if (rowModel.isRowAvailable() && columnsModel.isRowAvailable())
        {
            int columns = columnsModel.getRowIndex();
            if(rowModel.getRowIndex() == 2)
            {
                outputTextCell.setStyle("text-align: center; font-family: " +
                  "Georgia,'Times New Roman',times,serif; color: white; " +
                  "font-size: 12px;");
            }
            return ((List) rowModel.getRowData()).get(columns).toString();
        }
        return null;
    }


    public int getDaysOfMonth(int year, int month)
    {
        int daysOfMonth;
        GregorianCalendar gregorianCalendar = new GregorianCalendar(year, month, 1);
        System.out.println("---fecha: " + gregorianCalendar.getTime());
        daysOfMonth = gregorianCalendar.getActualMaximum(Calendar.DAY_OF_MONTH);
        return daysOfMonth;
    }

    /**
     * Rellena la tabla de fichajes para el mes que se le pasa por
     * paramentro
     * @param months MonthlySigning de los fichajes a mostrar
     * @return
     */
    private DataModel fillTableSigning(List<Event> listEvent)
    {
        Calendar calendarToDay = Calendar.getInstance();
        int daysMoth = getDaysOfMonth(calendarToDay.get(Calendar.YEAR),calendarToDay.get(Calendar.MONTH));

        arrayArrivalTime = new String[daysMoth + 1];
        arrayExitTime = new String[daysMoth +1];
        arrayTotalHours = new String[daysMoth +1];


        arrayArrivalTime[0] = getSessionBean1().getSessionBeanLanguage().getProperty("Hora_Entrada");
        arrayExitTime[0] = getSessionBean1().getSessionBeanLanguage().getProperty("Hora_Salida");
        arrayTotalHours[0] = getSessionBean1().getSessionBeanLanguage().getProperty("Total_Horas");

        if(listEvent.size() == 0)
        {
            for(int i = 1; i < daysMoth +1; i ++)
            {
              arrayArrivalTime[i] = "-";
              arrayExitTime[i] = "-";
              arrayTotalHours[i] = "-";
            }

        }
        else
        {
           Event eventF =  listEvent.get(0);

            Calendar c = Calendar.getInstance();
            c.setTimeInMillis(eventF.getDateTime().getTime());
            for(int i = 1; i < c.get(Calendar.DAY_OF_MONTH); i ++)
            {
              arrayArrivalTime[i] = "-";
              arrayExitTime[i] = "-";
              arrayTotalHours[i] = "-";
            }


            for(int i = c.get(Calendar.DAY_OF_MONTH); i < daysMoth + 1; i++ )
            {
                Calendar caux = Calendar.getInstance();
                caux.setTimeInMillis(eventF.getDateTime().getTime());
                caux.set(Calendar.DAY_OF_MONTH, i);
                Date date = new Date();
                date.setTime(caux.getTimeInMillis());

                EventJpaController eventJpaController = new EventJpaController();
                List<Event> lEvent = eventJpaController.findSigningByClientAndDay(eventF.getUser().getUserId(), date);
                if(lEvent.size()==0)
                {
                   arrayArrivalTime[i] = "-";
                   arrayExitTime[i] = "-";
                   arrayTotalHours[i] = "-";
                }
                else
                {
                    Event si = lEvent.get(0);
                    Event sl = lEvent.get(lEvent.size() - 1);
                    Calendar ci = Calendar.getInstance();
                    Calendar cl = Calendar.getInstance();

                    ci.setTimeInMillis(si.getDateTime().getTime());
                    cl.setTimeInMillis(sl.getDateTime().getTime());
                    int minutes = ci.get(Calendar.MINUTE);
                    String sMinute = new String();
                    if(minutes<10)
                    {
                       sMinute = "0"+String.valueOf(minutes);
                    }
                    else
                    {
                       sMinute = String.valueOf(minutes);
                    }

                    arrayArrivalTime[i] = ci.get(Calendar.HOUR_OF_DAY)+":"+sMinute;

                    if(si.equals(sl))
                    {
                        Calendar today = Calendar.getInstance();
                        if((ci.get(Calendar.DATE)==today.get(Calendar.DATE))&&(ci.get(Calendar.MONTH)==today.get(Calendar.MONTH)))
                        {
                             arrayExitTime[i] = "-";
                            arrayTotalHours[i] = "-";
                        }
                        else
                        {
                            arrayExitTime[i] = "23:59";
                            arrayTotalHours[i] = "-";
                        }

                    }
                    else if(lEvent.size() % 2 != 0)
                    {
                        Calendar today = Calendar.getInstance();
                        if((ci.get(Calendar.DATE)==today.get(Calendar.DATE))&&(ci.get(Calendar.MONTH)==today.get(Calendar.MONTH)))
                        {
                             arrayExitTime[i] = "-";
                            arrayTotalHours[i] = "-";
                        }
                        else
                        {
                            arrayExitTime[i] = "23:59";
                            arrayTotalHours[i] = "-";
                        }
                    }
                    else
                    {
                        minutes = cl.get(Calendar.MINUTE);
                        sMinute = new String();
                        if(minutes<10)
                        {
                            sMinute = "0"+String.valueOf(minutes);
                        }
                        else
                        {
                            sMinute = String.valueOf(minutes);
                        }
                        arrayExitTime[i] = cl.get(Calendar.HOUR_OF_DAY)+":"+sMinute;

                        arrayTotalHours[i] = CalcularDia(lEvent);
                    }
                }
            }
        }

        List listSingningViewTable = new ArrayList<ArrayList>();

        listSingningViewTable.add(0,
            new ArrayList(Arrays.asList(arrayArrivalTime)));
        listSingningViewTable.add(1,
            new ArrayList(Arrays.asList(arrayExitTime)));
        listSingningViewTable.add(2,
            new ArrayList(Arrays.asList(arrayTotalHours)));

        return new ListDataModel(listSingningViewTable);
    }


    private String CalcularDia(List<Event> listSigning)
    {
        if(listSigning.size() % 2 == 0)
        {
            Event si = listSigning.get(0);
            Event sl = listSigning.get(listSigning.size() - 1);
            Calendar ci = Calendar.getInstance();
            Calendar cl = Calendar.getInstance();
            ci.setTimeInMillis(si.getDateTime().getTime());
            cl.setTimeInMillis(sl.getDateTime().getTime());
            long total = 0;
            for(int i = 0; i < listSigning.size(); i ++)
            {
                si = listSigning.get(i);
                sl = listSigning.get(i+1);
                ci = Calendar.getInstance();
                cl = Calendar.getInstance();
                ci.setTimeInMillis(si.getDateTime().getTime());
                cl.setTimeInMillis(sl.getDateTime().getTime());
                long mi = ci.getTimeInMillis();
                long ml = cl.getTimeInMillis();
                total = total + (ml - mi);
                i++;
            }
            Calendar ct = Calendar.getInstance();
            ct.setTimeInMillis(total);

            int minutes = ct.get(Calendar.MINUTE);
            String sMinute = new String();
            if(minutes<10)
            {
                sMinute = "0"+String.valueOf(minutes);
            }
            else
            {
                sMinute = String.valueOf(minutes);
            }

            return ct.get(Calendar.HOUR)-1+":"+sMinute;
        }
        else
        {
            Event saux = listSigning.get(0);
            Calendar caux = Calendar.getInstance();
            caux.setTimeInMillis(saux.getDateTime().getTime());

            caux.set(Calendar.HOUR_OF_DAY, 23);
            caux.set(Calendar.MINUTE, 59);

            saux.setDateTime(caux.getTime());

            Event si = listSigning.get(0);
            Event sl = listSigning.get(listSigning.size() - 1);
            Calendar ci = Calendar.getInstance();
            Calendar cl = Calendar.getInstance();

            ci.setTimeInMillis(si.getDateTime().getTime());
            cl.setTimeInMillis(sl.getDateTime().getTime());

            long total = 0;
            for(int i = 0; i < listSigning.size(); i ++)
            {
                si = listSigning.get(i);
                sl = listSigning.get(i+1);

                ci = Calendar.getInstance();
                cl = Calendar.getInstance();

                 ci.setTimeInMillis(si.getDateTime().getTime());
                 cl.setTimeInMillis(sl.getDateTime().getTime());

                long mi = ci.getTimeInMillis();
                long ml = cl.getTimeInMillis();
                total = total + (mi - ml);
                i++;
            }

            Calendar ct = Calendar.getInstance();
            ct.setTimeInMillis(total);

            int minutes = ct.get(Calendar.MINUTE);
            String sMinute = new String();
            if(minutes<10)
            {
                sMinute = "0"+String.valueOf(minutes);
            }
            else
            {
                sMinute = String.valueOf(minutes);
            }

            return ct.get(Calendar.HOUR)-1+":"+sMinute;
        }
    }

    public void setPanelPopUp(String header, boolean visible)
    {
        this.getPanelPopup1Bean().setShowModalPanel(visible);
        this.getPanelPopup1Bean().setShowDraggablePanel(visible);
        this.setMessageHeader(header);
    }

    public boolean isDefaultAscending(String sortColumn)
    {
        return true;
    }

    /**
     *
     * @param inputText
     */
    public void changeColorInputText(HtmlInputText inputText)
    {
        if (inputText.getText().equals(""))
        {
            inputText.setStyle(colorEmptyField);
        }
        else
        {
            inputText.setStyle("");
        }
    }

    /**
     *
     * @param inputText
     */
    public void initColorInputText(HtmlInputText inputText)
    {
        inputText.setStyle("");
    }

    /**
     *
     * @param inputText
     */
    public void errorColorInputText(HtmlInputText inputText)
    {
        inputText.setStyle(colorEmptyField);
    }

    /**
     *
     * @param inputSecret
     */
    public void initColorInputSecret(HtmlInputSecret inputSecret)
    {
        inputSecret.setStyle("");
    }

    @Override
    public void init()
    {
        super.init();
        try
        {
            _init();
        }
        catch (Exception e)
        {
            log("Page1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }
    }

    @Override
    public void destroy()
    {
    }

    //////////////////////////////////////
    //getter y setter
    ///////////////////////////////////////
    private MainMenu getMainMenu() {
        MainMenu mainMenu = (MainMenu) getBean("MainMenu");
        return mainMenu;
    }

    protected RequestBean1 getRequestBean1() {
        return (RequestBean1) getBean("RequestBean1");
    }

    protected SessionBean1 getSessionBean1() {
        return (SessionBean1) getBean("SessionBean1");
    }

    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    public HtmlOutputLabel getLabelTittle() {
        return labelTittle;
    }

    public void setLabelTittle(HtmlOutputLabel labelTittle) {
        this.labelTittle = labelTittle;
    }

    public int getIdNumberEdit() {
        return idNumberEdit;
    }

    public void setIdNumberEdit(int idNumberEdit) {
        this.idNumberEdit = idNumberEdit;
    }

    public boolean isMultiRowSelect() {
        return multiRowSelect;
    }

    public void setMultiRowSelect(boolean multiRowSelect) {
        this.multiRowSelect = multiRowSelect;
    }

    public String getOldSort() {
        return oldSort;
    }

    public void setOldSort(String oldSort) {
        this.oldSort = oldSort;
    }

    public boolean isOldAscending() {
        return oldAscending;
    }

    public void setOldAscending(boolean oldAscending) {
        this.oldAscending = oldAscending;
    }

    public DataModel getColumnsModel()
    {
        if (columnsModel == null)
        {
            updateNumberColumns();
        }
        return columnsModel;
    }

    public void setColumnsModel(DataModel columnsModel)
    {
        this.columnsModel = columnsModel;
    }

    public CommandSortHeader getDayHeader() {
        return dayHeader;
    }

    public void setDayHeader(CommandSortHeader dayHeader) {
        this.dayHeader = dayHeader;
    }

    public HtmlOutputText getOutputTextCell() {
        return outputTextCell;
    }

    public void setOutputTextCell(HtmlOutputText outputTextCell) {
        this.outputTextCell = outputTextCell;
    }

    public DataModel getRowModel() {
        return rowModel;
    }

    public void setRowModel(DataModel rowModel) {
        this.rowModel = rowModel;
    }

    public PopupBean getPanelPopup1Bean() {
        return panelPopup1Bean;
    }

    public void setPanelPopup1Bean(PopupBean panelPopup1Bean) {
        this.panelPopup1Bean = panelPopup1Bean;
    }

    public String getMessageHeader() {
        return messageHeader;
    }

    public void setMessageHeader(String messageHeader) {
        this.messageHeader = messageHeader;
    }

    public DefaultSelectionItems getPanelSeries1Bean() {
        return panelSeries1Bean;
    }

    public void setPanelSeries1Bean(DefaultSelectionItems panelSeries1Bean) {
        this.panelSeries1Bean = panelSeries1Bean;
    }

    public HtmlCommandButton getBtnClosePopUp() {
        return btnClosePopUp;
    }

    public void setBtnClosePopUp(HtmlCommandButton btnClosePopUp) {
        this.btnClosePopUp = btnClosePopUp;
    }

    public List<User> getUserList() {
        return userList;
    }

    public void setUserList(List<User> userList) {
        this.userList = userList;
    }

    public PanelStack getPanelStack() {
        return panelStack;
    }

    public void setPanelStack(PanelStack panelStack) {
        this.panelStack = panelStack;
    }

    public HtmlOutputLabel getLabelDifferenceTime() {
        return labelDifferenceTime;
    }

    public void setLabelDifferenceTime(HtmlOutputLabel labelDifferenceTime) {
        this.labelDifferenceTime = labelDifferenceTime;
    }

    public HtmlOutputLabel getLabelDifferenceTimeResult() {
        return labelDifferenceTimeResult;
    }

    public void setLabelDifferenceTimeResult(HtmlOutputLabel labelDifferenceTimeResult) {
        this.labelDifferenceTimeResult = labelDifferenceTimeResult;
    }

    public HtmlOutputLabel getLabelEstimatedHours() {
        return labelEstimatedHours;
    }

    public void setLabelEstimatedHours(HtmlOutputLabel labelEstimatedHours) {
        this.labelEstimatedHours = labelEstimatedHours;
    }

    public HtmlOutputLabel getLabelTitlePanelMonthlySummary() {
        return labelTitlePanelMonthlySummary;
    }

    public void setLabelTitlePanelMonthlySummary(HtmlOutputLabel labelTitlePanelMonthlySummary) {
        this.labelTitlePanelMonthlySummary = labelTitlePanelMonthlySummary;
    }

    public HtmlOutputLabel getLabelTotalWorkingDays() {
        return labelTotalWorkingDays;
    }

    public void setLabelTotalWorkingDays(HtmlOutputLabel labelTotalWorkingDays) {
        this.labelTotalWorkingDays = labelTotalWorkingDays;
    }

    public HtmlOutputLabel getLabelTotalWorkingDaysResult() {
        return labelTotalWorkingDaysResult;
    }

    public void setLabelTotalWorkingDaysResult(HtmlOutputLabel labelTotalWorkingDaysResult) {
        this.labelTotalWorkingDaysResult = labelTotalWorkingDaysResult;
    }

    public HtmlOutputLabel getLabelTotalWorkingHours() {
        return labelTotalWorkingHours;
    }

    public void setLabelTotalWorkingHours(HtmlOutputLabel labelTotalWorkingHours) {
        this.labelTotalWorkingHours = labelTotalWorkingHours;
    }

    public HtmlOutputLabel getLabelTotalWorkingHoursResult() {
        return labelTotalWorkingHoursResult;
    }

    public void setLabelTotalWorkingHoursResult(HtmlOutputLabel labelTotalWorkingHoursResult) {
        this.labelTotalWorkingHoursResult = labelTotalWorkingHoursResult;
    }

    public HtmlOutputLabel getLabelEstimatedHoursResult() {
        return labelEstimatedHoursResult;
    }

    public void setLabelEstimatedHoursResult(HtmlOutputLabel labelEstimatedHoursResult) {
        this.labelEstimatedHoursResult = labelEstimatedHoursResult;
    }


}

